package com.jameci.luntan.service;

import com.jameci.luntan.dto.PaginationDTO;
import com.jameci.luntan.dto.PostDTO;
import com.jameci.luntan.mapper.PostMapper;
import com.jameci.luntan.mapper.UserMapper;
import com.jameci.luntan.model.Post;
import com.jameci.luntan.model.PostExample;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PostService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PostMapper postMapper;

    public PaginationDTO list(int page, int size) {
        PaginationDTO paginationDTO = new PaginationDTO();
        List<PostDTO> postDTOS = new ArrayList<PostDTO>();
        int totalCount = (int) postMapper.countByExample(new PostExample());
        if (page < 1) page = 1;
        int totalpage = Math.min(page, (totalCount + size - 1) / size);
        int offset = size * totalpage - size;
        List<Post> posts = postMapper.selectByExampleWithRowbounds(new PostExample(), new RowBounds(offset, size));
        for (Post post : posts) {
            PostDTO postDTO = new PostDTO();
            BeanUtils.copyProperties(post, postDTO);
            postDTO.setUser(userMapper.selectByPrimaryKey(post.getCreator()));
            postDTOS.add(postDTO);
        }
        paginationDTO.setPostDTOs(postDTOS);
        paginationDTO.setPaginationDTO(totalCount, page, size);
        return paginationDTO;
    }

    public PaginationDTO list(int page, int size, int creator) {
        PaginationDTO paginationDTO = new PaginationDTO();
        List<PostDTO> postDTOS = new ArrayList<PostDTO>();
        PostExample postExample = new PostExample();
        postExample.createCriteria().andCreatorEqualTo(creator);
        Integer totalCount = (int) postMapper.countByExample(postExample);
        if (page < 1) page = 1;
        page = Math.min(page, (totalCount + size - 1) / size);
        int offset = size * page - size;
        List<Post> posts = postMapper.selectByExampleWithBLOBsWithRowbounds(postExample, new RowBounds(offset, size));
        for (Post post : posts) {
            PostDTO postDTO = new PostDTO();
            BeanUtils.copyProperties(post, postDTO);
            postDTO.setUser(userMapper.selectByPrimaryKey(post.getCreator()));
            postDTOS.add(postDTO);
        }
        paginationDTO.setPostDTOs(postDTOS);
        paginationDTO.setPaginationDTO(totalCount, page, size);
        return paginationDTO;
    }

    public PostDTO getPostById(int id) {
        Post post = postMapper.selectByPrimaryKey(id);
        PostDTO postDTO = new PostDTO();
        BeanUtils.copyProperties(post, postDTO);
        postDTO.setUser(userMapper.selectByPrimaryKey(post.getCreator()));
        return postDTO;
    }
}
